package com.gitee.shigen.gateway.lb;

import java.util.List;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义随机算法
 * @see  com.netflix.loadbalancer.RoundRobinRule
 *
 */
@Slf4j
public class AlwaysFirstRule extends AbstractLoadBalancerRule {

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object key) {
        ILoadBalancer lb = this.getLoadBalancer();

        if (lb == null) {
            log.warn("no load balancer");
            return null;
        } else {
            Server server = null;
            List<Server> reachableServers = lb.getReachableServers();
            List<Server> allServers = lb.getAllServers();
            int upCount = reachableServers.size();
            int serverCount = allServers.size();
            if (upCount != 0 && serverCount != 0) {
                int index = 0;
                log.info("current server index: {}", index);
                return allServers.get(index);
            } else {
                log.warn("No up servers available from load balancer: {}", lb);
                return null;
            }
        }
    }
}
